﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Collections;
using MM.DBUtility;
using MM.Common;

namespace JobCostByDay
{
    public partial class Form1 : Form
    {
        private clsLogTool _log = new clsLogTool();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _log.LogFilePath = Directory.GetParent(Assembly.GetExecutingAssembly().Location) + "\\LOG\\";
            _log.LogFileName = "ErrorLog.txt";

            try
            {
                _log.WriteLog("============================JobStart==============================");
                DoJob();
                _log.WriteLog("Successful================JobEnd==============================");
            }
            catch (Exception ex)
            {
                _log.WriteLog(ex.ToString());
                _log.WriteLog("Failed====================JobEnd==============================");
            }
            this.Close();
        }

        private void DoJob()
        {
            //取得所有客户信息
            DataTable dtCNO = DbHelperSql.Query("SELECT CNO FROM T_Customers").Tables[0];
            if (dtCNO != null && dtCNO.Rows.Count > 0)
            {
                ArrayList SQLlist = new ArrayList();
                DataTable dtChannelNO = null, dtProvinceID = null;
                object OCNORate = null, OSIMCountByPID = null, OSIMAllCountByPID = null, OChannelRCountByPID = null;
                string strCNO = string.Empty, strChannelNO = string.Empty, strChannelPrice = string.Empty, strProvinceID = string.Empty;
                string strDayTime = DateTime.Now.ToString("yyyy-MM-dd");//当天日期
                int intSIMCountByPID = 0, intSIMAllCountByPID = 0;//当前客户编号+通道编号+省份的SMI条数，当前省份的SMI条数
                int intChannelRCountByPID = 0;//当前客户编号+通道编号+省份的通道返回记录数
                double dbeCountByPID = 0, dbeAllCount = 0, dbeAllMoney = 0;//当前客户编号+通道编号+省份的实际条数(计算后)，当前客户编号+通道编号的实际条数(计算后)
                double dbeCNORate = 0.8;//前客户编号的数据显示比例
                foreach (DataRow rowCNO in dtCNO.Rows)
                {
                    //在规则中取得正在使用的通道信息
                    strCNO = rowCNO["CNO"].ToString();
                    dtChannelNO = DbHelperSql.Query(string.Format("SELECT DISTINCT a.ChannelNO,a.ChannelPrice FROM T_Channel a,T_Rules b WHERE a.ChannelNO=b.ChannelNO AND b.CNO='{0}'", strCNO)).Tables[0];
                    if (dtChannelNO != null && dtChannelNO.Rows.Count > 0)
                    {
                        //取得当前客户编号的数据显示比例
                        try
                        {
                            OCNORate = DbHelperSql.GetSingle(string.Format("SELECT a.DataRate FROM  T_Users a,T_User_Customer b WHERE a.UserID=b.UserID AND b.CNO='{0}'", strCNO));
                            if (OCNORate != null && !string.IsNullOrEmpty(OCNORate.ToString()))
                            {
                                dbeCNORate = Convert.ToDouble(OCNORate);
                            }
                        }
                        catch { }

                        foreach (DataRow rowChannelNO in dtChannelNO.Rows)
                        {
                            //通过客户编号和通道编号，在规则中取得正在使用的省份信息
                            dbeAllCount = 0; dbeAllMoney = 0;//初始化总记录数
                            strChannelNO = rowChannelNO["ChannelNO"].ToString();
                            strChannelPrice = rowChannelNO["ChannelPrice"].ToString();
                            dtProvinceID = DbHelperSql.Query(string.Format("SELECT DISTINCT ProvinceID FROM T_Rules WHERE  Status='1' AND CNO='{0}' AND ChannelNO='{1}'", strCNO, strChannelNO)).Tables[0];
                            if (dtProvinceID != null && dtProvinceID.Rows.Count > 0)
                            {
                                foreach (DataRow rowProvinceID in dtProvinceID.Rows)
                                {
                                    strProvinceID = rowProvinceID["ProvinceID"].ToString();
                                    intSIMCountByPID = 0; intSIMAllCountByPID = 0; intChannelRCountByPID = 0;//初始化记录数
                                    dbeCountByPID = 0;
                                    //通过客户编号，通道编号，省份取得SIM记录数（当天）
                                    OSIMCountByPID = DbHelperSql.GetSingle(string.Format("SELECT COUNT(a.ID) FROM T_SIM a,T_Area b WHERE a.AreaNO=b.AreaNO AND a.ONO=b.ONO AND a.CNO='{0}' AND a.ChannelNO='{1}' AND b.ProvinceID={2} AND Format(a.CreateTime,'yyyy-MM-dd')='{3}'", strCNO, strChannelNO, strProvinceID, strDayTime));
                                    if (OSIMCountByPID != null && !string.IsNullOrEmpty(OSIMCountByPID.ToString()))
                                    {
                                        intSIMCountByPID = Convert.ToInt32(OSIMCountByPID);
                                        if (intSIMCountByPID > 0)
                                        {
                                            //通过通道编号+省份取得通道返回记录数（当天）
                                            OChannelRCountByPID = DbHelperSql.GetSingle(string.Format("SELECT COUNT(a.ID) FROM T_Receive a,T_Channel b WHERE a.destaddr=b.ChannelNumber AND a.msg=b.ChannelOrder AND a.ProvinceID={0} AND b.ChannelNO='{1}' AND Format(a.CreateTime,'yyyy-MM-dd')='{2}'", strProvinceID, strChannelNO, strDayTime));
                                            if (OChannelRCountByPID != null && !string.IsNullOrEmpty(OChannelRCountByPID.ToString()))
                                            {
                                                intChannelRCountByPID = Convert.ToInt32(OChannelRCountByPID);
                                                if (intChannelRCountByPID > 0)
                                                {
                                                    //通过编号+省份取得SIM记录数（当天）
                                                    OSIMAllCountByPID = DbHelperSql.GetSingle(string.Format("SELECT COUNT(a.ID) FROM T_SIM a,T_Area b WHERE a.AreaNO=b.AreaNO AND a.ONO=b.ONO AND b.ProvinceID={0} AND a.ChannelNO='{1}' AND Format(a.CreateTime,'yyyy-MM-dd')='{2}'", strProvinceID, strChannelNO, strDayTime));
                                                    if (OSIMAllCountByPID != null && !string.IsNullOrEmpty(OSIMAllCountByPID.ToString()))
                                                    {
                                                        intSIMAllCountByPID = Convert.ToInt32(OSIMAllCountByPID);
                                                        if (intSIMAllCountByPID > 0)
                                                        {
                                                            dbeCountByPID = Math.Truncate((intSIMCountByPID / intSIMAllCountByPID.ToDouble()) * intChannelRCountByPID * dbeCNORate);
                                                            dbeAllCount += dbeCountByPID;
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }
                            }
                            if (dbeAllCount > 0)
                            {
                                try
                                {
                                    dbeAllMoney = dbeAllCount * strChannelPrice.ToDouble();//算出总金额
                                }
                                catch { }
                                SQLlist.Add(string.Format("INSERT INTO T_Cost(CostDayTime,CNO,ChannelNO,SendNum,CostMoney) VALUES('{0}','{1}','{2}',{3},{4})", strDayTime, strCNO, strChannelNO, dbeAllCount, dbeAllMoney));
                            }
                        }
                    }
                }
                if (SQLlist.Count > 0)
                    MM.DBUtility.DbHelperSql.ExecuteSqlTran(SQLlist);
            }
            else
                _log.WriteLog("Do Nothing...");
        }
    }
}